package cn.szzsi._sys;

import cn.szzsi._Config;
import cn.szzsi.common.kit.SystemConfigUtil;
import cn.szzsi.common.model.*;
import cn.szzsi.common.model.zshop.CompanyInfo;
import cn.szzsi.common.model.zshop.Member;
import cn.szzsi.service.HtmlService;
import cn.szzsi.service.ProductService;
import cn.szzsi.service.SysHtmlService;
import com.jfinal.core.Controller;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.RecursiveTask;

public class ProductController extends Controller{
    private String shopId;
    // 列表
    public void list() {
        render("product_list.html");
    }
    //ajax product list
    public void ajaxlist(){
        int pageNumber=getParaToInt("pageNumber", 1);//第几页,默认1
        int pageSize=getParaToInt("pageSize", 10);//每页的数量,默认10if
        String name=getPara("name");
        String phone=getPara("phone");
        Member member=Member.dao.getByPhone(phone);

        String sql = "  from mall_product p left join mall_product_category pc on p.productCategory_id = pc.id  where  p.display=1 and p.isMarketable=true";
        if(StrKit.notBlank(name)){
            sql+=" and (p.name like '%"+name.trim()+"%' or pc.name like'%"+name.trim()+"%')";
        }
        if(member!=null){
            String shopId=member.getId();
            sql+=" and p.uid='"+shopId+"'";
        }
        sql+=" order by p.checked asc, p.modifyDate desc,p.createDate desc";
        Page<Product> page=Product.dao.paginate(pageNumber,pageSize,"select p.*,pc.name as categoryName ",sql);
        renderJson(page);

    }

    // 详情
    public void detail() {
        String id = getPara("productId","");
        Product product = Product.dao.findById(id);
        shopId=product.getUid();
        if(StrKit.notBlank(id)){
            setAttr("product", Product.dao.findById(id));
        }
        //setAttr("productCategoryTreeList", getProductCategoryTreeList());
        //上面代码注释,由原来的商户自己可以添加分类,改为平台给商户添加
        List<ProductCategory> productCategoryTreeList=null;
        CompanyInfo companyInfo=CompanyInfo.dao.getByShopId(shopId);
        String productCategoryId=companyInfo.getProductCategoryId();
        if(StrKit.notBlank(productCategoryId)){
            String productCategoryIdArry[]=productCategoryId.split(",");
            String ids="";
            for(int i=0;i<productCategoryIdArry.length;i++){
                ids+= JsonKit.toJson(productCategoryIdArry[i])+",";
            }
            if(ids.endsWith(",")){
                ids= ids.substring(0,ids.length()-1);
            }
            productCategoryTreeList=ProductCategory.dao.find("select * from mall_product_category where id in ("+ids+")");
            setAttr("productCategoryTreeList", productCategoryTreeList);
        }
        //上面代码注释,由原来的商户自己可以添加分类,改为平台给商户添加

        setAttr("allBrand", getAllBrand(shopId));
        setAttr("allWeightUnit", getAllWeightUnit());
        setAttr("allProductType", getAllProductType(shopId));
        //获取所有规格和规格值
        setAttr("allSpecification", Specification.me.getAllByCategoryIdAndShopId(null,shopId));
        //获取本系列所有的规格和规格值
        setAttr("specificationTypes", ProductService.service.getAllProductSpecificationType(product));
        setAttr("shopId",shopId);
        setAttr("systemConfig", SystemConfigUtil.getSystemConfig());
        setAttr("companyInfo",companyInfo);
        render("product_detail.html");
    }

    /**
     * 审核
     */
    public void checked(){
        final String productId=getPara("productId");
        String type=getPara("type");
        Boolean isBestPlateform=getParaToBoolean("isBestPlateform");
        Boolean isCheapPlateform=getParaToBoolean("isCheapPlateform");
        Boolean isNewPlateform=getParaToBoolean("isNewPlateform");
        Boolean isHotPlateform=getParaToBoolean("isHotPlateform");
        Boolean isTodayRecommend=getParaToBoolean("isTodayRecommend");
        final Product product=Product.dao.findById(productId);
        if(product!=null){
            product.setChecked(type);
            product.setIsBestPlateform(isBestPlateform);
            product.setIsCheapPlateform(isCheapPlateform);
            product.setIsNewPlateform(isNewPlateform);
            product.setIsHotPlateform(isHotPlateform);
            product.setIsTodayRecommend(isTodayRecommend);

        }
        product.update();
        //平台点击生成后,会自动生成商城首页,再此放到线程里面执行
        _Config.fixedThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                //1.生成平台店铺首页
                SysHtmlService.service.indexBuildHtml();
                //2.生成该商品的详情页
                SiteConfig siteConfig= SiteConfig.getByShopId(product.getUid());
                SysHtmlService.service.businessProductContentBuildHtml(product,siteConfig);
                //3.生成该商家店铺首页
                HtmlService.service.indexBuildHtml(siteConfig);

            }
        });
        renderJson(Ret.ok("info","操作成功!"));
    }

    //更改精品排序
    public void updateSortBestPlateform(){
        String id=getPara("id");
        Integer sortBestPlateform=getParaToInt("sortBestPlateform");
        Product product=Product.dao.findById(id);
        if(product!=null){
            product.setSortBestPlateform(sortBestPlateform);
            product.update();
            //平台更改后,重新生成平台首页
            _Config.fixedThreadPool.execute(new Runnable() {
                @Override
                public void run() {
                    //1.生成平台店铺首页
                    SysHtmlService.service.indexBuildHtml();
                }
            });
            renderJson(Ret.ok("info","操作成功!"));
        }else{
            renderJson(Ret.fail("info","商品不存在!"));
        }
    }

    /**
     * 更改特惠排序
     */
    public void updateSortCheapPlateform(){
        String id=getPara("id");
        Integer sortCheapPlateform=getParaToInt("sortCheapPlateform");
        Product product=Product.dao.findById(id);
        if(product!=null){
            product.setSortCheapPlateform(sortCheapPlateform);
            product.update();
            //平台更改后,重新生成平台首页
            _Config.fixedThreadPool.execute(new Runnable() {
                @Override
                public void run() {
                    //1.生成平台店铺首页
                    SysHtmlService.service.indexBuildHtml();
                }
            });
            renderJson(Ret.ok("info","操作成功!"));
        }else{
            renderJson(Ret.fail("info","商品不存在!"));
        }
    }

    public static void main(String[] args) {
        BigDecimal a=new BigDecimal(3);
        BigDecimal b=new BigDecimal(100);
        System.out.println(a.divide(b));
        System.out.println(a.divide(b).multiply(new BigDecimal(11.8)));
        System.out.println(a.divide(b).multiply(new BigDecimal(11.8)).setScale(2,BigDecimal.ROUND_HALF_UP));

    }

    /**
     * 更改商品返利百分比
     */
    public void updateProductRebatePercent(){
        String id=getPara("id");
        Integer productRebatePercent=getParaToInt("productRebatePercent");
        final Product product=Product.dao.findById(id);
        if(product!=null){
            BigDecimal percent=new BigDecimal(productRebatePercent).divide(new BigDecimal(100));//优惠百分比-->小数
            String specificationtype=product.getSpecificationtype();
            List<Product>commonProducts=Product.dao.getBySpecificationType(specificationtype);
            for(Product commonProduct:commonProducts){
                commonProduct.setProductRebatePercent(productRebatePercent);
                BigDecimal productRebatePercentMoney=commonProduct.getPrice().multiply(percent);//优惠后价格
                productRebatePercentMoney=productRebatePercentMoney.setScale(2,BigDecimal.ROUND_HALF_UP);//四舍五入保留两位小数
                commonProduct.setProductRebatePercentMoney(productRebatePercentMoney);
                commonProduct.update();
            }
            //平台更改后,重新生成平台首页
            _Config.fixedThreadPool.execute(new Runnable() {
                @Override
                public void run() {
                    //1.生成平台店铺首页
                    SysHtmlService.service.indexBuildHtml();
                    //2.生成该商品的详情页
                    SiteConfig siteConfig= SiteConfig.getByShopId(product.getUid());
                    SysHtmlService.service.businessProductContentBuildHtml(product,siteConfig);
                    //3.生成该商家店铺首页
                    HtmlService.service.indexBuildHtml(siteConfig);
                }
            });
            renderJson(Ret.ok("info","操作成功!"));
        }else{
            renderJson(Ret.fail("info","商品不存在!"));
        }
    }




    // 获取所有品牌
    public List<Brand> getAllBrand(String shopId) {
        return Brand.dao.getBusinessAll(shopId);
    }

    // 获取所有重量单位
    public List<Product.WeightUnit> getAllWeightUnit() {
        List<Product.WeightUnit> allWeightUnit = new ArrayList<Product.WeightUnit>();
        for (Product.WeightUnit weightUnit : Product.WeightUnit.values()) {
            allWeightUnit.add(weightUnit);
        }
        return allWeightUnit;
    }

    // 获取所有商品类型
    public List<ProductType> getAllProductType(String shopId) {
        return ProductType.dao.getAllByShopId(shopId);
    }

}
